package com.mj.action.system;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mj.base.BaseController;
import com.mj.model.system.Role;
import com.mj.model.system.User;
import com.mj.service.system.RoleService;
import com.mj.service.system.UserService;
import com.mj.util.PasswordHelper;

/**
 * 用户管理
 *@ClassName:UserAction.java
 *@author dsc
 *@date 2017年7月20日
 *@Description TODO
 *
 */
@Controller
@RequestMapping("user")
public class UserAction extends BaseController {
	@Resource
	private UserService userService;
	@Resource
	private RoleService roleService;
	@Resource
    private PasswordHelper passwordHelper;
	//登录拦截
	@RequestMapping(value = "login")  
    public String showLoginForm( Model model) { 
		Subject subject = SecurityUtils.getSubject();
		//如果用户登录状态已存在，则返回到首页，防止用户后退登录，一直跳转在登录页面
		if(StringUtils.isNotEmpty((String) subject.getPrincipal())){
			return "redirect:/"; 
		}else{
			String exceptionClassName = (String)request.getAttribute("shiroLoginFailure");  
	        String error = "";  
	        if(UnknownAccountException.class.getName().equals(exceptionClassName)) {  
	            error = "用户名/密码错误";  
	        } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {  
	            error = "用户名/密码错误";  
	        } else if(ExcessiveAttemptsException.class.getName().equals(exceptionClassName)) {  
	            error = "输入错误次数过多,10分钟后重试！";  
	        } else if(LockedAccountException.class.getName().equals(exceptionClassName)){
	        	error = "抱歉，该账号已被冻结！";  
	        } else if(ExpiredCredentialsException.class.getName().equals(exceptionClassName)){
	        	error = "凭证过期！"; 
	        }
	        if(request.getParameter("forceLogout") != null) {
	        	error = "您已经被管理员强制退出，请重新登录";
	        }
	        if(request.getParameter("kickout") != null) {
	        	error = "登录已失效，请重新登录";
	        }
	        log.info(error);
	        model.addAttribute("error", error);  
	        return "login"; 
		}
    }  
	//用户列表页面
	@RequestMapping(value = "")  
	public String toUserlist(Model model){
		List<Role> rlist = roleService.findAllRoleList(null);
		model.addAttribute("rlist", rlist);
		/*List<User> users = userService.findAll();
		for(User u: users){
			if(u.getUsername()!="admin"){
				passwordHelper.encryptPassword(u);
				 userService.updateById(u);
			}
		}*/
		return "system/user/user_list";
	}
	
	//用户编辑页面
	@RequestMapping(value = "to_user_edit")  
	public String userEdit(){
		return "system/user/edit";
	}
	
	//用户退出
	@RequestMapping(value = "logout")  
	public String logout( Model model) {
		Subject subject = SecurityUtils.getSubject();
		log.info("用户退出！"+subject.getPrincipal());
		subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
		log.info(subject);
		return "redirect:/"; 
	}
	/**
	 * @param user
	 * @param map
	 * @param pageSize 页面条数
	 * @param pageIndex 页码
	 * @param startDate 开始日期
	 * @param endDate 结束日期
	 * @param userName 账号
	 * @param mobileNum 手机号
	 * @param sort 排序规则
	 * @param order 排序字段
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "userlist")
	 public String ulist(User user,@RequestParam Map<String,Object> map) {
		//查询用户总数
		int totalNum = userService.countUser(map);
		List<Map<String,Object>> ulist = userService.findall(map);
		return renderJsonGrid(ulist, totalNum);
	 }
	
	/**
	 * 编辑用户信息
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="editUser")
	public Boolean editUser(User user){
		passwordHelper.encryptPassword(user);
		int flag = userService.updateById(user);
		log.info(SecurityUtils.getSubject().getPrincipal()+"用户修改-uid:"+user.getUserId());
		if(flag > 0){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * 添加用户
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="addUser")
	public Boolean addUser(User user){
		int flag = userService.addUser(user);
		if(flag > 0){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 批量删除用户
	 */
	@ResponseBody
	@RequestMapping(value="delUser")
	public boolean delUser(){
		String ids[] = request.getParameter("ids").split(",");
		userService.delUserById(ids);
		return true;
	}
	
	
	//判断新增用户名是否已存在
	@ResponseBody
	@RequestMapping(value="isExistsUser")
	public String ExistsUser(){
		
		return "";
	}
	/**
	 * 查询用户
	 */
	@ResponseBody
	@RequestMapping(value="getUserById")
	public String getUserById(){
		User u = userService.findById(Integer.valueOf(request.getParameter("uid")));
		return renderJson(u);
	}
	
	//冻结、解冻用户
	@ResponseBody
	@RequestMapping(value="toLockUser")
	public Boolean lockUser(){
		int status = Integer.parseInt(request.getParameter("status"));
		int sta = status == 1 ? 0 : 1;//如果status=1 ，赋值0.status=0，赋值1 
		int uid = Integer.parseInt(request.getParameter("userId"));
		int flag = userService.setUserStatus(sta, uid);
		log.info("用户状态修改-uid:"+uid);
		if(flag>0){
			return true;
		}else{
			return false;
		}
	}
	
	
	//重置密码
	@ResponseBody
	@RequestMapping(value="resetPass")
	public Boolean resetPass(){
		int userId = Integer.parseInt(request.getParameter("userId"));
		boolean flag = userService.resetPWD(userId);
		log.info("重置用户密码-uid:"+userId);
		return flag;
	}
	
	/**
	 * 导入用户数据
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping(value="importUser")
	public Boolean addUserExcel(@RequestParam(value = "filePath", required = false)MultipartFile filePath) throws IOException{
		return userService.importUserData(filePath);
	}
	
	/**
	 * 导出用户数据
	 * @param response
	 * @param request
	 * @return
	 * @throws Exception 
	 * 备注，导出的数据列中不能出现空值
	 */
	@ResponseBody
	@RequestMapping(value="exportUser")
	public void exportUser() throws Exception{
		//文件名，时间戳格式
		String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
		//头信息
        String headStr = "attachment; filename=\"" + fileName + "\"";  
		response.setContentType("APPLICATION/OCTET-STREAM");  
        response.setHeader("Content-Disposition", headStr);  
        OutputStream out = response.getOutputStream();
        userService.exportUserData(out);
	}
	
	/** 
	* @Title: validataUsername 
	* @Description: TODO(验证用户登录名是否唯一) 
	* @param @param id
	* @param @param name
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws 
	*/
	@RequestMapping(value = "validataUsername", method = RequestMethod.POST)
	@ResponseBody
	public String validataUsername(String id,String name){
		
		String result="false";
			User user =userService.selectByName(name);
			if(id.equals("")&&user==null||!id.equals("")&&user==null){
				System.out.println("idxx------"+id);
				result = "true";
			}
			if(!id.equals("")){
				if(user!=null&&user.getUserId().equals(Long.valueOf(id))){
					System.out.println("idss------"+id);
					result = "true";
				}
			}
		return result;
	}
	
	
	/**
	 * 跳转登录页面
	 * @return
	 */
	@RequestMapping("toupdatePass")
	public String toupdatePass(){
		return "system/user/changePass";
	}
	
	/**
     * 修改密码
     * 
     * @param model
     * @param req
     * @return
     * @author dsc
     */
    @ResponseBody
    @RequestMapping("changePWD")
    public String changePass(@RequestParam Map<String,Object> map, HttpServletRequest req){
    	map.put("user", getUser());
        String flag = userService.updatePass(map);
        return flag;
    }
	/** 
	* @Title: userBind 
	* @Description: TODO(用户下拉菜单数据绑定) 
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws 
	*/
	@RequestMapping(value = "userBind", method = RequestMethod.GET)
	@ResponseBody
	public String actorBind(){
		List<User> user = userService.findAll();
		Gson gson = new GsonBuilder().registerTypeAdapter(User.class,
				new JsonSerializer<User>() {
					@Override
					public JsonElement serialize(User arg0, Type arg1,
							JsonSerializationContext arg2) {
						JsonObject json = new JsonObject();
						json.addProperty("id", arg0.getUserId());
						json.addProperty("name", arg0.getName()+" "+arg0.getUsername());
						json.addProperty("mobile", arg0.getMobileNumber());
						return json;
					}
				}).create();
		return gson.toJson(user);
	}
}
